package com.jp.fm;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.PrefixFileFilter;

public class TestHelper {
	public static void setupTestDb() throws IOException {
		// Map<String, String> env = System.getenv();
		// Get the test DB dir
		// String testDbDirStr = env.get("TEST_DB_PATH");
		URL fileUrl = TestHelper.class.getResource("/HomeFinanceTest.script");
		File dbFile = FileUtils.toFile(fileUrl);
		String testDbDirStr = FilenameUtils.getFullPath(dbFile
				.getAbsolutePath());
		File testDbPath = new File(testDbDirStr);

		// Delete any existing test DB files and copy over fresh ones
		Collection<File> testDbFilesToDelete = FileUtils.listFiles(testDbPath,
				new PrefixFileFilter("HomeFinanceTest"), new PrefixFileFilter(
						"HomeFinanceTest"));

		for (File file : testDbFilesToDelete) {
			FileUtils.forceDelete(file);
		}

		// Copy original test Db files to runtime location.
		Collection<File> testDbFilesToCopy = FileUtils.listFiles(new File(
				"./unit/"), new PrefixFileFilter("HomeFinanceTest"), null);

		for (File file : testDbFilesToCopy) {
			FileUtils.copyFileToDirectory(file, testDbPath);
		}
	}
}
